/**
 * Created by Administrator on 17-6-14.
 */
!
$(function () {
    //禁用拖拽时打开新标签
    document.body.ondrop = function (event) {
        event.preventDefault();
        event.stopPropagation();
    }
    // tooltips
    $('[data-toggle="tooltip"]').tooltip();
    $("[data-toggle=popover]").popover();
    //单选多选
    checksFun();
    //初始化下拉框的搜索输入
    initSelectSearch();
    //搜索条件展开
    advSearchFun();
    //点击面包屑
    $(".Jump-box").click(function () {
        var id = $(this).data('id');
        var type = $(this).data('type');
        var jumpEm = window.parent.document.getElementById("jump-box-input");
        var redirectEvent = new CustomEvent('jump-event',{
            detail : {
                'id':id,
                'type':type
            }
        });
        jumpEm.dispatchEvent(redirectEvent);
    });
});
var winArea = ['80%','80%'];

/**
 * 获取所有的专业列表，且分层归类好的
 * @returns 专业列表
 */
function findLayeredSubjectList() {
    var subjectList = null;
    $.ajax({
        url:baseloaction+'/admin/manage/subject/findLayeredSubjectList',
        dataType:'json',
        async:false,
        success:function (result) {
            if(result.success==false){
                icModale(0,result.message);
            }else{
                subjectList = result.entity;
            }
        },
        error:function (error) {
            icModale(0,"系统错误，初始化专业/科目失败");
        }
    });
    return subjectList;
}

/**
 * 获取Tree树结构的所有的节点数量
 * @param treeId 树ID
 * @return {number} 节点数量
 */
function getCount(treeId) {
    var _count = 0;
    var zTreeObj = $.fn.zTree.getZTreeObj(treeId);
    var parentList = zTreeObj.getNodes();
    if(!$.isEmptyObject(parentList)){
        recursionCount(parentList);
        return _count;
    }
    /**递归获取所有的节点量*/
    function recursionCount(list) {
        _count += list.length;
        $.each(list,function (index,node) {
            var childList = node.children;
            if(!$.isEmptyObject(childList)){
                recursionCount(childList);
            }
        });
    }
    return 0;
}

/**
 * 获取页面上的A标签跳转的菜单刷新
 * @param urls 跳转的路径
 * @param tag 是否要提示
 */
function getRedirectMenu(urls, tag) {
    if (tag == false) {
        _redirectMenu();
    } else {
        icModale(2, "即将离开当前页面，跳转到新页面去？", 3, function () {
            _redirectMenu();
        });
    }
    function _redirectMenu() {
        $.ajax({
            url: baseloaction +'/admin/manage/getRedirectMenu',
            data:{'url':urls},
            type:"post",
            dataType:'json',
            success:function (result) {
                if(result.success==true){
                    var list =result.entity;
                    var parentFn = list[0];
                    var oneFn = list[1];
                    var twoFn = list[2];
                    var em = window.parent.document.getElementById("redirect-input");
                    var redirectEvent = new CustomEvent('redirect-event',{
                        detail : {
                            'parentId':parentFn.id,
                            'oneId':oneFn.id,
                            'twoId':twoFn.id,
                            'uri':urls
                        }
                    });
                    em.dispatchEvent(redirectEvent);
                }else {
                    icModale(0, result.message);
                }
            },
            error:function (error) {
                icModale(0, '系统错误，跳转失败');
            }
        });
    }
}

/**
 * 获取右则页面主内容中，当前在显示的iframe的name属性
 */
function contentMainIframeName() {
    var _iframe = $("#main-body-context iframe:visible", window.parent.document);
    var index = _iframe.length - 2;
    return _iframe[index].name;
}

/**
 * 获取右则页面主内容中，当前在显示的iframe的name属性
 */
function contentParentMainIframeName() {
    var _iframe = $("#main-body-context iframe:visible");
    return _iframe[0].name;
}

//========================文件上传，开始===========================
//默认管理员图片的规格(比例：1/1)
var DEFAULT_SYS_USER_IMG_SIZE = {
    pc: {
        large: {width: 380, height: 380}
    },
    mobile: {
        large: {width: 180, height: 180}
    }
};
//默认课程图片的规格(比例：16/9)
var DEFAULT_COURSE_IMG_SIZE = {
    pc: {
        large: {width: 510, height: 286},
        medium: {width: 220, height: 124},
        small: {width: 380, height: 380}
    },
    mobile: {
        large: {width: 414, height: 234},
        small: {width: 248, height: 140}
    }
};
//默认老师图片的规格(比例：1/1)
var DEFAULT_TEACHER_IMG_SIZE = {
    pc: {
        large: {width: 380, height: 380}
    },
    mobile: {
        large: {width: 180, height: 180}
    }
};
//默认文库图片的规格(比例：2/3)
var DEFAULT_LIBRARY_IMG_SIZE = {
    pc: {
        large: {width: 162, height: 200}
    },
    mobile: {
        large: {width: 162, height: 200}
    }
};

//默认图书图片的规格(比例：2/3)
var DEFAULT_BOOK_IMG_SIZE = {
    pc: {
        large: {width: 227, height: 340},
        small: {width: 147, height: 220}
    },
    mobile: {
        large: {width: 134, height: 200}
    }
};
//默认资讯图片的规格(比例：16/9)
var DEFAULT_ARTICLE_IMG_SIZE = {
    pc: {
        large: {width: 580, height: 334},
        medium: {width: 279, height: 150},
        small: {width: 100, height: 56}
    },
    mobile: {
        large: {width: 580, height: 334},
        medium: {width: 279, height: 150},
        small: {width: 100, height: 56}
    }
};
//默认知识付费图片的规格(比例：1/1.3)
var DEFAULT_LORE_IMG_SIZE = {
    mobile: {
        large: {width: 200, height: 260}
    }
};
//默认班级图片的规格(比例：1/1)
var DEFAULT_CLASS_IMG_SIZE = {
    pc: {
        small: {width: 380, height: 380}
    },
    mobile: {
        small: {width: 180, height: 180}
    }
};
window['DEFAULT_SYS_USER_IMG_SIZE'] = DEFAULT_SYS_USER_IMG_SIZE;
window['DEFAULT_COURSE_IMG_SIZE'] = DEFAULT_COURSE_IMG_SIZE;
window['DEFAULT_TEACHER_IMG_SIZE'] = DEFAULT_TEACHER_IMG_SIZE;
window['DEFAULT_LIBRARY_IMG_SIZE'] = DEFAULT_LIBRARY_IMG_SIZE;
window['DEFAULT_BOOK_IMG_SIZE'] = DEFAULT_BOOK_IMG_SIZE;
window['DEFAULT_ARTICLE_IMG_SIZE'] = DEFAULT_ARTICLE_IMG_SIZE;
window['DEFAULT_LORE_IMG_SIZE'] = DEFAULT_LORE_IMG_SIZE;
window['DEFAULT_CLASS_IMG_SIZE'] = DEFAULT_CLASS_IMG_SIZE;

//删除图片
function removePageImg() {
    $('input[name="imageJson"]').val('');
    $("#coverImage img").attr("src", staticPath+"/admin/v3/img/default/default-pic.jpg");
    $("#coverImage #file-names").text('图片名');
    $("#coverImage #create-time").text('上传时间');
}

//========================文件上传，结束===========================
//=================================时间控件初始化，开始=================
function initLayerDate(selector, time) {
    var format = time ?  'YYYY-MM-DD hh:mm:ss' : 'YYYY-MM-DD';
    if ($(selector).length > 0) {
        laydate({
            elem: selector,
            format: format,
            istime: time
        });
    }
}
//=================================时间控件初始化，结束=================
/**
 * 初始化下拉框的搜索输入
 */
function initSelectSearch() {
    //下拉搜索选择
    var config = {
        '.chosen-select': {},
        '.chosen-select-deselect': {
            allow_single_deselect: true
        },
        '.chosen-select-no-single': {
            disable_search_threshold: 10
        },
        '.chosen-select-no-results': {
            no_results_text: 'Oops, nothing found!'
        },
        '.chosen-select-width': {
            width: "95%"
        },
        '.chosen-select-no-search': {
            disable_search: true
        }
    };
    for (var selector in config) {
        $(selector).chosen(config[selector]);
    }
}

/**
 * 验证表单数据，各个要验证的元素添加一个class='validate-data'
 */
function validateData() {
    var arr = $('.validate-data');
    if (!$.isEmptyObject(arr) && arr.length > 0) {
        $.each(arr, function (index, em) {
            if ((em.tagName == 'INPUT' && (em.type == 'text' || em.type == 'hidden')) || em.tagName == 'TEXTAREA') {
                $(em).keyup(function () {
                    if($(em).hasClass('number')){
                        var value = $(this).val();
                        if(!/^(\d+)$/.test(value)){
                            $(this).val('');
                        }
                    }else{
                        _classHasError($.isEmptyObject(this.value) || $.trim(this.value) == '', em);
                    }
                });
            } else if (em.tagName == 'SELECT') {
                $(em).change(function () {
                    _classHasError($.isEmptyObject(this.value) || this.value == '0', em);
                });
            }
        });
    }
}

function _classHasError(status, em) {
    if (status) {
        $(em).parent().addClass('has-error');
    } else {
        $(em).parent().removeClass('has-error');
    }
}

/**
 * 单选框选择
 * @param em
 * @param callback 选择回调
 */
function inputRadioSel(em, callback) {
    $(em).on("ifClicked", function (event) {
        callback(event.target);
    });
}

/**
 * switch开关选择
 * @param em
 * @param callback 选择回调
 */
function onOffSwitchSel(em, callback) {
    $(em).on("change", function (event) {
        callback(event.target);
    });
}

//chekbox状态判断
function allSelete(id, callback) {
    $("#" + id).on("ifClicked", function (event) {
        if (event.target.checked) {//未选中
            callback(false);
        } else {//选中
            callback(true);
        }
    });
}

//单选多选
function checksFun() {
    if ($('.i-checks').length > 0) {
        $('.i-checks').iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green'
        });
    }
}

//advSearch
var advSearchFun = function () {
    var flag = false;
    $('body').on('click', '#advSearchshowBtn', function () {
        var formArr = $(".search-form");
        if(formArr!=null && formArr.length>0){
            $(formArr).each(function (index,em) {
                var _id = $(em).attr('id');
                if(typeof _id=='undefined' || _id==null ||_id==''){
                    $(em).attr("id",'search-form');
                }else{
                    $(em).removeAttr("id");
                }
            });
        }
        var that = $(this);
        if (!flag) {
            that.html('收起高级操作 <i class="fa fa-angle-double-up"></i>');
            $('.opSearchBox').hide();
            $('.oc-advSearch-box').show();
            flag = true;
            var _name = $(".opSearchBox .common-search-word").attr('name');
            $(".opSearchBox .common-search-word").attr('name', '');
            $(".oc-advSearch-box .common-search-word").attr('name', _name);
        } else {
            that.html('高级搜索操作 <i class="fa fa-angle-double-down"></i>');
            $('.opSearchBox').show();
            $('.oc-advSearch-box').hide();
            flag = false;
            var _name = $(".oc-advSearch-box .common-search-word").attr('name');
            $(".oc-advSearch-box .common-search-word").attr('name', '');
            $(".opSearchBox .common-search-word").attr('name', _name);
        }
    }).on('keyup',".common-search-word",function(){
        var _this = $(this);
        var val = _this.val();
        $(".common-search-word").val(val);
    });
}

//折叠ibox
$('body').on('click', '.collapse-link', function () {
    var that = $(this),
        ibox = that.closest('div.ibox'),
        button = that.find('i'),
        content = ibox.find('div.ibox-content');
    content.slideToggle(200);
    button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
    ibox.toggleClass('').toggleClass('border-bottom');
    setTimeout(function () {
        ibox.resize();
        ibox.find('[id^=map-]').resize();
    }, 50);
})

//scrollUnique
$.fn.scrollUnique = function () {
    return $(this).each(function () {
        var eventType = 'mousewheel';
        if (document.mozHidden !== undefined) {
            eventType = 'DOMMouseScroll';
        }
        $(this).on(eventType, function (event) {

            var scrollTop = this.scrollTop,
                scrollHeight = this.scrollHeight,
                height = this.clientHeight;

            var delta = (event.originalEvent.wheelDelta) ? event.originalEvent.wheelDelta : -(event.originalEvent.detail || 0);

            if ((delta > 0 && scrollTop <= delta) || (delta < 0 && scrollHeight - height - scrollTop <= -1 * delta)) {
                // IE浏览器下滚动会跨越边界直接影响父级滚动，因此，临界时候手动边界滚动定位
                this.scrollTop = delta > 0 ? 0 : scrollHeight;
                // 向上滚 || 向下滚
                event.preventDefault();
            }
        });
    });
}

//基本弹层
/**
 *   type: 类型：0，1，2。分别为：提示层，弹出层，询问层
 *   icon: 图标：0，1，2，3。分别为：警告，正确，错误，疑问
 *   content: 文本内容
 *   callback: 按钮回调
 */
function icModale(type, content, icon, callback) {
    if (content == null) {
        content = "没有提示信息内容";
    }
    var index = 0;
    switch (type) {
        case 0:
            index = parent.layer.msg(content);
            break
        case 1:
            index = parent.layer.alert(content, {
                icon: icon,
                title: '提示'
            }, function () {
                if ($.isFunction(callback)){
                    callback(index)
                }
                parent.layer.close(index);
            });
            break
        case 2:
            index = parent.layer.confirm(content, {
                icon: icon,
                title: '提示',
                btn: ['确认', '取消'],
                shade: [0.3, '#000000']
            }, function () {
                if ($.isFunction(callback)){
                    callback(index);
                }
                parent.layer.close(index);
            });
            break
    }
}

//-----------------------------------初始化summernote，开始---------------------
/**
 * 初始化文本编辑器
 * @param obj {
 *          id:初始化的目标元素ID，
 *          toolsArr:工具栏数组,
 *          height:高度,
 *          gs:公式开关,
 *          isWin:是否是窗口默认不是}
 * @return {jQuery}
 */
function initSNU(obj) {
    var toolsArr = null;
    if (typeof obj.toolsArr != 'undefined' && obj.toolsArr != null) {
        toolsArr = obj.toolsArr;
    } else {
        toolsArr = [
            // 撤消, 重做
            ["remove", ["undo", "redo"]],
            // 字体,字体大小,字体颜色,粗体,斜体
            ["font", ["fontname", "fontsize", "color", "bold", "italic"]],
            // 样式,序列表,无序列表,段落,行高
            ["para", ["style", "ol", "ul", "paragraph", "height"]],
            // 链接插入 ,图片上传 ,视频 ,表格, <hr/>
            ["insert", ["link", "myImage", "table", "hr"]],
            //下划线,中划线,居上,居下,清除格式
            ["para", ["underline", "strikethrough", "superscript", "subscript", "clear"]]
        ];
        if (obj.gs == true) {
            var arr = ["view", ["codeview", "fullscreen", "myGS"]];
            toolsArr.push(arr);
        } else {
            var arr = ["view", ["codeview", "fullscreen"]];
            toolsArr.push(arr);
        }
    }
    var em = null;
    if(obj.type==1){//全部本页面操作
        em = $("#"+obj.id);
    }else if(obj.type==2){//弹框，但弹框内容不是iframe加载的，而拼接的HTML内容
        em = parent.$("#"+obj.id);
    }
    var $summernote = $(em).summernote({
        lang: 'zh-CN',
        height: obj.height ? obj.height : 400,
        minHeight: 300,
        maxHeight: 500,
        focus: false,
        dialogsInBody: true,
        toolbar: toolsArr,
        buttons: {
            myvideo: function (context) {
                var ui = $.summernote.ui;
                // create button
                var button = ui.button({
                    contents: '<i class="note-icon-video"/>',
                    tooltip: '视频',
                    click: function () {
                        var winContext = '<div class="m-t m-r m-l m-b">';
                        winContext += '<select id="videoType" class="form-control mb10">';
                        winContext += '<option value="96K">268云服务</option>';
                        winContext += '</select>';
                        winContext += '<input class="form-control" value="" id="vidoCode" type="text">';
                        winContext += '</div>';

                        var index = parent.layer.open({
                            type: 1,
                            shadeClose: false,
                            area: ['380px'],
                            skin: 'layui-layer-demo',
                            title: '请填写视频播放码',
                            content: winContext,
                            btn: '确定',
                            yes: function (index, layero) {
                                var vidoCode = layero.find("#vidoCode").val();
                                var videoType = layero.find("#videoType").val();
                                if (videoType == '96K') {
                                    var div = document.createElement('div');
                                    vidoCode = $.trim(vidoCode);
                                    div.innerHTML = '<object width="99%" height="99%" id="96k_'+vidoCode+'" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="https://v.96koo.net/static/video/96k.swf?videoId='+vidoCode+'" name="movie"><param name="wmode" value="transparent"><param value="true" name="allowFullScreen"><param value="always" name="allowScriptAccess"><param value="videoId='+vidoCode+'" name="FlashVars"><embed width="99%" height="99%" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" name="96k_'+vidoCode+'" src="http://v.96koo.net/static/video/96k.swf?videoId='+vidoCode+'"></object>';
                                    context.invoke('editor.insertNode', div);
                                }
                                parent.layer.close(index);
                            }
                        });
                    }
                });
                return button.render();
            },
            myGS: function (context) {
                var ui = $.summernote.ui;
                var button = ui.button({
                    contents: '<i class="fa fa-gbp fs16"/>',
                    tooltip: '选择KityFormula公式',
                    click: function () {
                        var winContext = baseloaction + '/kityformula-plugins/kityFormulaLayer.html#'+mydomain;
                        var index = parent.layer.open({
                            type: 2,
                            shadeClose: false,
                            area: ['820px', '545px'],
                            skin: 'layui-layer-demo',
                            title: '插入KityFormula公式',
                            content: winContext,
                            btn: '确定',
                            yes: function (index, layero) {
                                parent.window.frames['layui-layer-iframe' + index].getImageURL(function (imgUrl) {
                                    $summernote.summernote('insertImage', imgUrl);
                                    parent.layer.close(index);
                                });
                            }
                        });
                    }
                });
                return button.render();
            },
            myImage: function (context) {
                var ui = $.summernote.ui;
                var button = ui.button({
                    contents: '<i class="note-icon-picture"/>',
                    tooltip: '上传图片',
                    click: function () {
                        var winContext = '<div class="m-t m-r m-l m-b">';
                        winContext += '选择图片<input type="file" id="fileInput" class="form-control"/><br/>';
                        winContext += '或填写图片路径<input class="form-control" value="" id="imageUrl" type="text"/>';
                        winContext += '</div>';
                        var index = parent.layer.open({
                            type: 1,
                            shadeClose: false,
                            area: ['500px'],
                            skin: 'layui-layer-demo',
                            title: '插入图片',
                            content: winContext,
                            btn: '确定',
                            yes: function (index, layero) {
                                var file = layero.find("#fileInput")[0].files[0];
                                var imageUrl = layero.find("#imageUrl").val();
                                if (typeof file == 'undefined' && (imageUrl == null || $.trim(imageUrl) == '')) {
                                    icModale(0, "请选择图片或填写有效的图片路径");
                                    return;
                                }
                                if (imageUrl == null || $.trim(imageUrl) == '') {
                                    var fileData = new FormData();
                                    fileData.append("file", file);
                                    $.ajax({
                                        url: baseloaction + '/admin/uploadFile',
                                        type: 'post',
                                        data: fileData,
                                        cache: false,
                                        contentType: false,
                                        processData: false,
                                        success: function (result) {
                                            if (result.success == true) {
                                                var imgObj = result.entity;
                                                $summernote.summernote('insertImage', imgObj.url, function ($image) {
                                                    $image.css({
                                                        'max-width': '100%',
                                                        'height' : 'auto'
                                                    }).attr("alt",imgObj.fileName);
                                                    parent.layer.close(index);
                                                });
                                            } else {
                                                icModale(0, obj.message);
                                            }
                                        },
                                        error: function (error) {
                                            icModale(0, "系统错误，文件上传失败");
                                        }
                                    });
                                } else {
                                    $summernote.summernote('insertImage', imageUrl, function ($image) {
                                        $image.css({
                                            'max-width': '100%',
                                            'height' : 'auto'
                                        });
                                        parent.layer.close(index);
                                    });
                                }

                            }
                        });
                    }
                });
                return button.render();
            }
        },
        callbacks: {
            onImageUpload: function (files) {
                var file = files[0];
                var fileData = new FormData();
                fileData.append("file", file);
                $.ajax({
                    url: baseloaction + '/admin/uploadFile',
                    type: 'post',
                    data: fileData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (result) {
                        if (obj.success == true) {
                            var imgObj = result.entity;
                            $summernote.summernote('insertImage', imgObj.url, function ($image) {
                                $image.attr('alt', imgObj.fileName);
                            });
                        } else {
                            icModale(0, obj.message);
                        }
                    },
                    error: function (error) {
                        icModale(0, "系统错误，文件上传失败");
                    }
                });
            }
        }
    });
    return $summernote;
}

//-----------------------------------初始化summernote，结束---------------------

//---------------------------------页面加载数据公用方法，开始-------------------
/**
 * 加截列表页面数据
 * @param url 请求URL （必选）
 * @param contextId 页面设置内容ID （必选）
 * @param params 请求参数 （可选）
 * @param pageNo 页码 （可选）
 * @param pageCall 分页回调 （可选）
 * @param selectAllId 全选框ID （可选）
 */
function ajaxGetListData(obj) {
    var _params = '';
    var pageNo = 1;
    if (typeof obj.pageNo != 'undefined' && obj.pageNo != 'undefined' && obj.pageNo != null && obj.pageNo != 'undefined') {
        pageNo = obj.pageNo;
    }
    if (!$.isEmptyObject(obj.params) && $.trim(obj.params) != '') {
        _params += obj.params;
    }
    $.ajax({
        url: obj.url+"?currentPage="+pageNo,
        data: _params,
        dataType: 'text',
        type:'post',
        contentType:'application/json;charset=utf-8',
        async: false,
        beforeSend: function (XHR) {
            var loadText = '<div class="icLoading"><span>&nbsp;</span></div>';
            $("#" + obj.contextId).html(loadText);
            return true;
        },
        success: function (result) {
            $("#" + obj.contextId).html(result);
            $("#"+obj.selectAllId).iCheck('uncheck');
            setEndTrTd();
            // tooltips
            $('[data-toggle="tooltip"]').tooltip();
            $("#select-page-no").change(function () {
                if (obj.pageCall != 'undefined' && $.isFunction(obj.pageCall)) {
                    obj.pageCall(this.value);
                }
            });

            $("#page-list-box>li").each(function () {
                var _this = $(this);
                if (!_this.hasClass('disabled') && !_this.hasClass('active')) {
                    _this.click(function () {
                        var _pageNo = $(this).attr('data-no');
                        if (obj.pageCall != 'undefined' && $.isFunction(obj.pageCall)) {
                            obj.pageCall(_pageNo);
                            $('html,body').scrollTop(0)
                        }
                    });
                }
            });
            var _checks = $("#" + obj.contextId + " .i-checks"), _length = _checks.length;
            //初始化多选框
            if (!$.isEmptyObject(_checks) && _length > 0) {
                checksFun();
                //初始化全选按钮关联
                if (!$.isEmptyObject(obj.selectAllId) && typeof obj.selectAllId != 'undefined') {
                    allSelete(obj.selectAllId, function (status) {
                        if (status) {
                            $("#" + obj.contextId).find('.i-checks').iCheck('check');
                        } else {
                            $("#" + obj.contextId).find('.i-checks').iCheck('uncheck');
                        }
                    });
                    _checks.on('ifChanged', function (event) {
                        var _len = $("#" + obj.contextId + " div").filter('.checked').length;
                        if (event.target.checked) {
                            _len++;
                        } else {
                            _len--;
                        }
                        if (_len == _length) {
                            $("#" + obj.selectAllId).iCheck('check');
                        } else {
                            $("#" + obj.selectAllId).iCheck('uncheck');
                        }
                    });
                }
            }
            if (obj.callback != 'undefined' && $.isFunction(obj.callback)) {
                obj.callback(obj.pageNo);
            }
        },
        error: function (error) {
            icModale(0, '系统错误，数据加载失败');
        }
    });
}


//---------------------------------页面加载数据公用方法，结束-------------------
//设置最后一行的显示标签
function setEndTrTd() {
    //设置最后一行的显示标签
    var table = $("table.table-xs-content");
    var trList = table.find("tr").not('.jqgfirstrow');
    if(trList!=null && trList.length > 0){
        var length = trList.length;
        if(length==1){//只有一行
            var oneTr = trList[0];
            $(oneTr).find('[data-toggle="tooltip"]').data("placement", "left");
        }else if(length == 2){//只有两行
            var oneTr = trList[0];
            $(oneTr).find('[data-toggle="tooltip"]').data("placement", "bottom");
            var twoTr = trList[1];
            $(twoTr).find('[data-toggle="tooltip"]').data("placement", "top");
        }else{
            var oneTr = trList[0];
            $(oneTr).find('[data-toggle="tooltip"]').data("placement", "bottom");
            var endTr = trList[length - 1];
            $(endTr).find('[data-toggle="tooltip"]').data("placement", "top");
        }
    }
}

/**
 * 验证正整数
 * @param str
 * @returns {boolean}
 */
function isNumber(str) {//正整数验证
    var number = /^[0-9]+$/;
    if (number.test(str)) {
        return true;
    }
    return false;
}

/**
 * 验证数字和字母
 * @param str
 * @returns {boolean}
 */
function isLettersAndNumbers(str) {//验证数字和字母
    var isLettersAndNumbers = /^[a-zA-Z0-9]+$/;
    if (isLettersAndNumbers.test(str)) {
        return true;
    }
    return false;
}

/**
 * 验证小数点后只能存在两位
 * @param str
 * @returns {boolean}
 */
function isDecimalAndInteger(str) {//验证正整数和小数
    var decimalAndInteger = /^[\d]+\.?[\d]{0,2}$/;
    if (decimalAndInteger.test(str)) {
        return true;
    }
    return false;
}

/**
 * 获得选中的记录id
 * @returns {string}
 */
function getChecked(status,checked) {
    var ids = checked.map(function () {
        var parent = $(this).parents('tr');
        if (predicate(parent, status)) {
            return this.value;
        }
    }).get().join(',');
    if(checked.length==0){
        return '';
    }else {
        if(!ids){
            return '-1';
        }else {
            return ids;
        }
    }
}

/**
 * 是否获取该条记录的id的谓词
 * @param parent tr元素
 * @param status 更新后的状态
 * @returns {boolean}
 */
function predicate(parent, status) {
    switch (status) {
        case 1:
            return parent.find('i.fa-arrow-up, i.fa-history').length > 0;
        case 2:
            return parent.find('i.fa-unlock-alt').length > 0;
        case 3:
            return parent.find('i.fa-trash').length > 0;
        default:
            return false;
    }
}

/**
 * 去掉头尾指定字符
 * @param val 原字符串
 * @param str 要替换的字符
 * @returns {*} 返回处理后的字符串
 */
function subHeadTailStr(val,str) {
    if(val!=null && $.trim(val) !=''){
        var rg = new RegExp("^"+str+"*");
        val = val.replace(rg, '');

        rg = new RegExp(str);
        var i = val.length;
        while (rg.test(val.charAt(--i)));
        val = val.slice(0, i + 1);
    }
    return val;
}


/**
 * 把数字转成字母
 * @param number 数字
 * @returns {string} 转成字母
 */
function numberToCharCode(number) {
    return String.fromCharCode(number);
}

/**
 * 把字母转成数字
 * @param charCode 字母
 * @returns {number} 数字
 */
function charCodeToNumber(charCode) {
    return charCode.charCodeAt();
}

function lazyCourseImage() {
    //图片数据懒加载
    $('img.lazy').lazyload({
        placeholder: staticPath + '/front/web/v3/img/default/default-course.gif',  //占位图
        effect: 'fadeIn',//载入方式
        threshold: 200, // 提前开始加载
    });
}

/**
 * 加载讲师图片
 */
function lazyTeacherImage() {
    //图片数据懒加载
    $('img.lazy').lazyload({
        placeholder: staticPath + '/front/web/v3/img/default/default-face.gif',  //占位图
        effect: 'fadeIn' ,//载入方式
        threshold: 200, // 提前开始加载
    });
}

/**
 * 将 N秒 处理为 N小时N分钟N秒 字符串
 * @param longTime 秒
 * @returns {string}
 */
function longTimeToStr(longTime) {
    let strTime = "";
    longTime = longTime * 1;
    if (longTime){
        let hour = parseInt(longTime / 3600);
        if(hour > 0){
            strTime += hour + "小时";
        }
        let minute = parseInt((longTime % 3600) / 60);
        if (minute > 0){
            strTime += minute + "分钟";
        }
        let sec = (longTime % 60);
        strTime += sec + "秒";
    }else{
        strTime = "0秒"
    }
    return strTime;
}

